package com.gitee.cirnochat.common.exception;


import com.gitee.cirnochat.chat.model.enums.MessageOperation;
import com.gitee.cirnochat.websocket.model.vo.resp.WebSocketMessageResponse;
import io.swagger.v3.oas.annotations.Hidden;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.handler.annotation.MessageExceptionHandler;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.ControllerAdvice;

import java.security.Principal;

import static com.gitee.cirnochat.common.constant.WebSocketConstant.ERRORS_SUBSCRIBE_CHANNEL;

/**
 * 全局websocket消息异常处理器
 * @author FlanChan
 */
@ControllerAdvice
@Hidden
@Slf4j
@RequiredArgsConstructor
public class GlobalMessageExceptionHandler {
    private final SimpMessagingTemplate messagingTemplate;

    @MessageExceptionHandler(BusinessException.class)
    public void handleException(BusinessException e, Principal principal) {
        log.error("WebSocket消息业务处理异常", e);
        messagingTemplate.convertAndSendToUser(principal.getName(), ERRORS_SUBSCRIBE_CHANNEL,
                WebSocketMessageResponse.Builder
                .code(e.getCode().getValue())
                .message(e.getMessage())
                .operation(MessageOperation.NOTIFY)
                .build());
    }

    @MessageExceptionHandler(MessageBusinessException.class)
    public void handleException(MessageBusinessException e, Principal principal) {
        log.error("WebSocket消息业务处理异常", e);
        messagingTemplate.convertAndSendToUser(principal.getName(), ERRORS_SUBSCRIBE_CHANNEL,
                WebSocketMessageResponse.Builder
                        .code(e.getCode())
                        .messageId(e.getMessageId())
                        .message(e.getMessage())
                        .operation(MessageOperation.SEND_ERROR)
                        .build());
    }
}
